/*
 * Cell.cpp
 *
 *  Created on: Apr 24, 2017
 *      Author: zhangjf
 */

#include <Poco/Dynamic/Var.h>

using namespace Poco::Dynamic;

#include "Cell.h"

namespace cell
{

Cell::Cell(std::string& cellType, std::string& appType, UInt32 nIID)
: NcsObject()
, _cellType(cellType)
, _appType(appType)
, _iid(nIID)
, _runningStatus(CELL_RUNNING_STATUS::CREATING)
{
}

void Cell::setRunningStatus(CELL_RUNNING_STATUS status)
{
	RunningStatusParams params;
	params.oldStatus = _runningStatus;
	params.newStatus = status;

	_runningStatus = status;

	doRunningStatusChanged(this, params);
}

bool Cell::initialize()
{
	bool blRet = true;
	return blRet;
}

void Cell::runTask()
{
	try
	{
		while (!isCancelled())
		{
			Notification* pNotif = _nq.waitDequeueNotification();

			handleNotification(pNotif);
			Task::sleep(10);
		}
	}
	catch(...)
	{
		poco_information(CellSubsystem::instance().logger(), "exception occurred when running...");
	}
}

template<typename T>
void Cell::recallPropertyValue(std::string& strProp)
{
	std::string strValue;
	Cell::Ptr pThis(this);
	//DirectoryServices::getCellProperty(pThis, strProp, strValue);
	_mapProperty[strProp] = strValue;
}

template<typename T>
void Cell::rewritePropertyValue(std::string& strProp, Var& val)
{
	Cell::Ptr pThis(this);
	//DirectoryServices::setCellProperty(pThis, strProp, strValue);
	_mapProperty[strProp] = val;
}

template<typename T>
T Cell::getPropertyValue(std::string strProp)
{
	if (_mapProperty.find(strProp) == _mapProperty.end())
	{
		recallPropertyValue<T>(strProp);
	}

	T value = (T)_mapProperty[strProp];

	return value;
}

template<typename T>
void Cell::setPropertyValue(std::string strProp, T value)
{
	T v = getPropertyValue<T>(strProp);

	if (v != value)
	{
		Var v = value;

		rewritePropertyValue<T>(strProp, v);
	}
}

void Cell::setAppName(std::string& strName)
{
	AppNameChangedParams params;

	params.oldAppName = _appType;
	params.newAppName = strName;

	_appName = strName;

	doAppNameChanged(this, params);

}

void Cell::enqueueNotification(Notification::Ptr pNotification)
{
	_nq.enqueueNotification(pNotification);
}

void Cell::handleNotification(Notification* pNotif)
{
	if (pNotif != nullptr)
	{
		poco_information(CellSubsystem::instance().logger(), "ToDo:: handle nofitication...");
	}
}

} /* namespace cell */

